package com.itheima.aop;

import com.itheima.doman.Result;
import com.itheima.doman.pojo.Emp;
import com.itheima.doman.pojo.EmpLoginLog;
import com.itheima.doman.pojo.LoginInfo;
import com.itheima.mapper.EmpLoginMapper;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

//@Aspect
//@Component
@Slf4j
public class EmpLoginAspect {
    @Autowired
    private EmpLoginMapper empLoginMapper;
    @Around("@annotation(com.itheima.anno.Login)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        log.info("员工登录切面开始执行");
        long start = System.currentTimeMillis();
        Object result = null;
        EmpLoginLog empLoginLog = new EmpLoginLog();
        Object[] args = pjp.getArgs();
        // 从方法参数中获取Emp对象
        if (args != null && args.length > 0) {
            for (Object arg : args) {
                if (arg instanceof Emp) {
                    Emp emp = (Emp) arg;
                    empLoginLog.setUsername(emp.getUsername());
                    empLoginLog.setPassword(emp.getPassword());
                    break;
                }
            }
        }
        empLoginLog.setLoginTime(LocalDateTime.now());
        
        try {
            result = pjp.proceed();
            return result;
        } finally {
            long end = System.currentTimeMillis();
            empLoginLog.setCostTime(end - start);
            
            // 从返回结果中获取JWT令牌
            if (result instanceof Result) {
                Result resultObj = (Result) result;
                empLoginLog.setIsSuccess(resultObj.getCode().shortValue());

                // 如果登录成功，从data中获取JWT令牌
                if (resultObj.getCode() == 1 && resultObj.getData() != null) {
                    if (resultObj.getData() instanceof LoginInfo) {
                        LoginInfo loginInfo = (LoginInfo) resultObj.getData();
                        empLoginLog.setJwt(loginInfo.getToken());
                    }
                }
                // 这里可以保存登录日志到数据库
                empLoginMapper.insertLog(empLoginLog);
            }
        }
    }
}